<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Yy</title>
    <style>
        body {
            height: 2000px;
        }
        
        .to-top {
            position: fixed;
            bottom: 100px;
            right: 100px;
            display: none;
        }
    </style>
</head>

<body>
    <h1>hello world</h1>
    <button class="to-top">↑</button>
    <script>
        // 4. 分别利用防抖和节流实现返回顶部的效果。
        let toTop = document.querySelector(".to-top");
        toTop.onclick = function() {
            window.scrollTo(0, 0);
        }
        window.onscroll = throttle(() => {
            if (document.documentElement.scrollTop > 0) {
                toTop.style.display = "inline-block"
            } else {
                toTop.style.display = "none"
            }
        }, 500);

        function throttle(fn, delay) {
            let mark = true;
            return function() {
                if (mark) {
                    setTimeout(() => {
                        fn();
                        mark = true
                    }, delay)
                }
                mark = false;
            }
        }
    </script>
</body>

</html>